package com.whl.sm.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.dto.SysMenuDto;
import com.whl.sm.dto.TransferDto;
import com.whl.sm.mapper.system.UserCpRoleMapper;
import com.whl.sm.model.system.*;
import com.whl.sm.service.system.*;
import com.whl.sm.vo.OrgUserRoleVo;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-09-10
 */
@Service
public class UserCpRoleServiceImpl extends ServiceImpl<UserCpRoleMapper, UserCpRole> implements UserCpRoleService {

    @Autowired
    private MenuCpRoleService menuCpRoleService;

    @Autowired
    private SysMenuService sysMenuService;


    @Autowired
    private UserCpComService userCpComService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OrgUserService orgUserService;


    @Override
    public List<SysMenuDto> getUserMenuTree(String userId) {
            List<SysMenu> menuTree;
            UserCpRole userCpRole = getBaseMapper().selectOne(new QueryWrapper<UserCpRole>().eq("user_id",userId));
            List<String> menuIdList = menuCpRoleService.getMenusByRelateRoleId(userCpRole.getRoleId());
            List<SysMenu> menuList =  sysMenuService.list(new QueryWrapper<SysMenu>()
                    .in("id",menuIdList)
                    .orderByDesc("create_time")
            );
            menuTree = buildTreeMenu(menuList);
        return convert(menuTree);
    }

    @Override
    public int updateUserRole(UserCpRole userCpRole) {
        getBaseMapper().delete(new QueryWrapper<UserCpRole>().eq("user_id",userCpRole.getUserId()));
        userCpRole.setOperator("sys");
        getBaseMapper().insert(userCpRole);
        return 0;
    }

    @Override
    public List<TransferDto> getComMagUserList() {
        List<Role> comMagRoles =  roleService.list(new QueryWrapper<Role>().eq("type","2"));
        List<UserCpCom> userCpComList = userCpComService.list();
        List<String> roleIds = comMagRoles.stream().map(Role::getId).collect(Collectors.toList());
        QueryWrapper<UserCpRole>  queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",roleIds);
        List<UserCpRole> magUser = list(queryWrapper);
        List<OrgUser> magUserDetail = magUser.stream().map(ucr ->{
            OrgUser user = orgUserService.getById(ucr.getUserId());
            return user;
        }).collect(Collectors.toList());
        return convertTransfer(magUserDetail);
    }

    @Override
    public Result getByCurrent(String userId) {
        Role role = new Role();
        try {
            List<UserCpRole> linkList  = getBaseMapper().selectList(new QueryWrapper<UserCpRole>().eq("user_id",userId));
            if (linkList.size()>0){
                role = roleService.getById(linkList.get(0).getRoleId());
            }
        }catch (Exception e){
           log.error("获取当前用户角色信息失败:"+e.getMessage());
        }
        return Result.ok(role);
    }


    private List<SysMenu> buildTreeMenu(List<SysMenu> menus) {
        List<SysMenu> finalMenus = new ArrayList<>();
        for (SysMenu menu : menus) {               // 先寻找各自的孩子
            for (SysMenu e : menus) {
                if (e.getParentId().equals(menu.getId())) {
                    menu.getChildren().add(e);
                }
            }         // 提取出父节点
            if (menu.getParentId().equals("0")) {
                finalMenus.add(menu);
            }
        }
        return finalMenus;
    }

    //左侧结构树转换
    private List<SysMenuDto> convert(List<SysMenu> menus) {
        List<SysMenuDto> menuDtos = new ArrayList<>();
        menus.forEach(m -> {
            SysMenuDto dto = new SysMenuDto();
            dto.setId(m.getId());
            dto.setName(m.getPerms());
            dto.setTitle(m.getMenuName());
            dto.setComponent(m.getComponent());
            dto.setIcon(m.getIcon());
            dto.setPath(m.getPath());
            if (m.getChildren().size() > 0) {
                dto.setChildren(convert(m.getChildren()));
            }
            menuDtos.add(dto);
        });
        return menuDtos;
    }


    //左侧结构树转换
    private List<TransferDto> convertTransfer(List<OrgUser> users) {
        List<TransferDto> transferDtos = new ArrayList<>();
        users.forEach(m -> {
            TransferDto dto = new TransferDto();
            dto.setKey(m.getId());
            dto.setLabel(m.getLoginName());
            dto.setDisabled(false);
            transferDtos.add(dto);
        });
        return transferDtos;
    }

}
